package io.github.wppli.domain.websocket.service;

import cc.jq1024.middleware.token.service.ITokenService;
import lombok.Getter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.stereotype.Service;


import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author li--jiaqiang 2025−03−05
 */
@Getter
@Service
public class WebsocketServerService {

    private static final Logger log = LoggerFactory.getLogger(WebsocketServerService.class);


    private final ITokenService tokenService;


    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
     */
    private static final CopyOnWriteArraySet<WebsocketServerService> webSocketSet = new CopyOnWriteArraySet<>();

    /**
     * 连接数
     */
    private static final AtomicInteger count = new AtomicInteger();

    /**
     * 用户id，一开始使用前端传入的方式，但是有安全隐患，后来换成后端从security中获取
     */
    private String userId = "";

    public WebsocketServerService(ITokenService tokenService) {
        this.tokenService = tokenService;
    }

    public void onOpen(StompHeaderAccessor accessor) {
        // 获取线程ID
        Long threadId = Thread.currentThread().getId();

        // 从 STOMP 头部获取 Token（例如 Authorization 头）
        String tokenHeader = accessor.getFirstNativeHeader("Authorization");
        log.info("threadId:{} HeaderToken: {}", threadId, tokenHeader);
        if (tokenHeader == null || !tokenHeader.startsWith("Bearer ")) {
            log.info("TokenHeader startsWith Bearer: false");
            throw new AuthenticationCredentialsNotFoundException("Token缺失或格式错误");
        }
        String token = tokenHeader.substring(7);
        String userId = tokenService.decode(token).getSubject();
        for (WebsocketServerService webSocket : webSocketSet) {
            if (webSocket.userId.equals(userId)) {
                webSocketSet.remove(webSocket);
                count.getAndDecrement();
            }
        }
        this.userId = userId;
        webSocketSet.add(this);
        count.getAndIncrement();
        log.info("threadId: {}, 有新连接加入-用户：{}！当前在线人数为:{}", threadId, this.userId, count.get());
    }

    /**
     * 连接关闭调用的方法
     */
    public void onClose() {
        for (WebsocketServerService webSocket : webSocketSet) {
            if (webSocket.userId.equals(userId)) {
                webSocketSet.remove(webSocket);
                count.getAndDecrement();
                // 获取线程ID
                Long threadId = Thread.currentThread().getId();
                log.info("threadId:{} 有一连接关闭-用户：{}！当前在线人数为:{}", threadId, this.userId, count.get());
            }
        }
    }

    /**
     * 判断用户是否在线
     */
    public boolean isOnline(String userId) {
        for (WebsocketServerService webSocket : webSocketSet) {
            if (webSocket.userId.equals(userId)) {
                return true;
            }
        }
        return false;
    }


}